<!--
 * @Descripttion: your project
 * @version: 1.0
 * @Author: hongweixun
 * @Date: 2023-05-17 16:06:06
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-11-04 10:01:44
-->
<template>
    <div class="screenRtTwo">
        <Title>
            <template #title>
                今日用餐刷脸/刷卡峰值
            </template>
        </Title>
        <div v-show="!props.isNodate" class="chartBox" ref="chartOneRef"
            :style="'height:' + (props.screenRtTwoHeight - $util.fontSize(40)) + 'px;'">
            <div ref="chartRef" class="chart"></div>
        </div>
        <div v-if="props.isNodate" class="chartBox" ref="chartOneRef"
            :style="'height:' + (props.screenRtTwoHeight - $util.fontSize(40)) + 'px;'">
            <NoDate title="暂无数据"></NoDate>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import $util from "../util/util"
import * as echarts from 'echarts';
import { PiniaStore } from '../store/index'
import { ElMessage } from 'element-plus'
import { todayFacultyPayUserCountByHour } from './Options/Api'
interface PropsType {
    screenRtTwoHeight?: number
    isNodate?: boolean
}
const props = withDefaults(defineProps<PropsType>(), {
    screenRtTwoHeight: 0,
    isNodate: false,
})
const store = PiniaStore()
const list = ref<any>([])
const getList = async () => {
  const res: any = await todayFacultyPayUserCountByHour()
  if (res.code !== 1) return ElMessage.error(res.msg)
  return new Promise(async (resolve) => {
    list.value = res.data.list
    initChart()
    store.setLoddingStatus()
    // 所有操作完成后resolve
    resolve(undefined) 
  })
}
const chartRef = ref<any>(null);
let myChart: any = null;
const initChart = async () => {
    myChart = echarts.init(chartRef.value)
    let typeList: any[] = []
    
    // 辅助函数：将时间段转换为中间时间点
    const getMiddleTime = (timeRange: string): string => {
        try {
            // 分割时间段字符串
            const [startTime, endTime] = timeRange.split(' ~ ')
            if (!startTime || !endTime) return timeRange
            
            // 解析开始时间
            const [startHour, startMinute] = startTime.split(':').map(Number)
            // 解析结束时间
            const [endHour, endMinute] = endTime.split(':').map(Number)
            
            // 计算总分钟数的平均值
            const startTotalMinutes = startHour * 60 + startMinute
            const endTotalMinutes = endHour * 60 + endMinute
            const middleTotalMinutes = (startTotalMinutes + endTotalMinutes) / 2
            
            // 转换回小时和分钟
            const middleHour = Math.floor(middleTotalMinutes / 60)
            const middleMinute = Math.round(middleTotalMinutes % 60)
            
            // 格式化输出（分钟部分补零）
            return `${middleHour}:${middleMinute.toString().padStart(2, '0')}`
        } catch (error) {
            console.error('时间格式转换错误:', error)
            return timeRange
        }
    }
    
    // 1. 初始化数据结构，用于存储多组数据
    let facultyMap = new Map<string, any[]>()
    let facultyNames: string[] = []
    let allData: any[] = []
    let fullTypeList: any[] = [] // 存储原始时间段
    
    // 2. 处理数据并提取多组数据
    if (list.value && list.value.length > 0) {
        // 先获取所有学部名称
        const firstFacultyList = list.value[0].faculty
        if (firstFacultyList && Array.isArray(firstFacultyList)) {
            firstFacultyList.forEach(faculty => {
                if (faculty && faculty.faculty_name) {
                    facultyNames.push(faculty.faculty_name)
                    facultyMap.set(faculty.faculty_name, [])
                }
            })
        }
        
        // 遍历所有时间段的数据
        list.value.forEach((item: any) => {
            fullTypeList.push(item.time_period)
            
            // 处理每个时间段的学部数据
            if (item.faculty && Array.isArray(item.faculty)) {
                item.faculty.forEach((faculty: any) => {
                    if (faculty && faculty.faculty_name && facultyMap.has(faculty.faculty_name)) {
                        const value = faculty.pay_user_count || 0
                        facultyMap.get(faculty.faculty_name)?.push(value)
                        allData.push(value)
                    }
                })
            }
        })
        
        // 转换时间段为中间时间点
        typeList = fullTypeList.map(timeRange => getMiddleTime(timeRange))
    }
    
    // 3. 定义颜色数组
    let baseColors = ['#46EDE8', '#FDAA1B', '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
    let color = facultyNames.map((_, index) => {
        if (index < baseColors.length) return baseColors[index]
        return `hsl(${(index * 40) % 360}, 70%, 60%)`
    })
    
    // 4. 计算坐标轴刻度
    let maxVal = allData.length > 0 ? Number(Math.max(...allData)) * 1.3 : 100
    let minVal = 0
    let interval = Math.ceil(maxVal / 5)
    maxVal = Math.ceil(maxVal / interval) * interval
    
    // 5. 使用循环生成series数组
    const series = facultyNames.map((name, index) => ({
        name: name,
        type: 'bar',
        activeName: name,
        barGap: 0,
        barWidth: $util.fontSize(14),
        itemStyle: {
            normal: {
                color: color[index]
            }
        },
        data: facultyMap.get(name) || []
    }))
    console.log(fullTypeList,'9999999999999999')
    var option = {
        color: color,
        title: {
            text: `单位/笔数`,
            top: $util.fontSize(28),
            left: $util.fontSize(12),
            textStyle: {
                color: '#FFFFFF',
                fontSize: $util.fontSize(14),
                fontWeight: 'normal'
            }
        },
        tooltip: {
            trigger: 'axis',
            backgroundColor: "#fff",
            extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
            formatter: function (params: any) {
                // 使用axisValueIndex获取当前数据点的索引，然后从fullTypeList中获取原始时间段
                const originalTimeRange = fullTypeList[params[0].dataIndex] || params[0].name;
                return (
                    `<span style='font-size: 12px;
                                font-family: Source Han Sans CN, Source Han Sans CN;
                                font-weight: bold;
                                color: #0A1F48;margin-left:-2px;margin-bottom:4px;display:inline-block;'>${originalTimeRange}</span>` +
                    `<br>` +
                    params.map((item: any, index: number) => {
                        let str = `<span style="display:inline-block;vertical-align: middle;width:8px;height:8px;margin: 0 5px 0 0px;background-color:${color[index]};"></span>`
                        let seriesNameStr = `<span style="display:inline-block;font-size:12px;vertical-align: middle;">${item.seriesName}</span>`
                        let value = item.value
                        let valueStr = `<span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;">${value}笔</span>`
                        return `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                                    <span>${str}${seriesNameStr}</span>
                                    <span>${valueStr}</span>
                                </span>`
                    })
                        .join(``)
                )
            },
        },
        grid: {
            left: $util.fontSize(18),
            right: $util.fontSize(18),
            bottom: $util.fontSize(20),
            top: $util.fontSize(74),
            containLabel: true
        },
        legend: {
            orient: 'horizontal',
            icon: 'circle',
            top: $util.fontSize(28),
            right: $util.fontSize(18),
            itemGap: $util.fontSize(20),
            itemWidth: 9,
            itemHeight: 9,
            textStyle: {
                color: '#fff',
                fontSize: $util.fontSize(16),
                width: 200,
                rich: {
                    a: {
                        verticalAlign: 'middle',
                    },
                },
                padding: [3, 0, 0, 4],
            },
            data: facultyNames,
        },
        xAxis: [
            {
                type: 'category',
                axisLine: {
                    lineStyle: {
                        type: 'solid',
                        color: '#535572',//左边线的颜色
                        width: '1'//坐标线的宽度
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#ffffff',//坐标值得具体的颜色
                        fontSize: $util.fontSize(14),
                    },
                    interval: 1
                },
                axisTick: false,
                data: typeList
            }
        ],
        yAxis: [
            {
                type: 'value',
                min: minVal, // 坐标轴刻度最小值。
                max: maxVal, // 坐标轴刻度最大值。
                interval: interval, // 强制设置坐标轴分割间隔，确保刻度均匀分布
                minInterval: 1,
                scale: true,
                axisLine: {
                    lineStyle: {
                        type: 'solid',
                        color: '#2E3950',//左边线的颜色
                        width: '1',//坐标线的宽度
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#ffffff',//坐标值得具体的颜色
                        fontSize: $util.fontSize(14),
                    }
                },
                axisTick: false,
                splitLine: {  //坐标轴在grid区域中的分隔线（网格中的横线）
                    show: true,
                    lineStyle: {
                        color: ['#535572'],
                        width: 1,
                        type: 'dashed',
                    }
                }
            }
        ],
        series: series
    }
    myChart.setOption(option)
}
//重新加载图表
const reloadChart = () => {
    disposeChart()
    initChart()
}
const disposeChart = () => {
    if (myChart) {
        myChart.dispose();
    }
}
watch(
    () => props.screenRtTwoHeight,
    (newVal: any) => {
        nextTick(() => {
            reloadChart()
        })
    },
    { deep: true }
)
onMounted(async () => {
    window.addEventListener("resize", () => {
        setTimeout(() => {
            reloadChart()
        }, 500)
    });
})
defineExpose({ getList })
</script>
<style lang="scss" scoped>
.screenRtTwo {
    margin-top: 24px;
    background: rgba(0, 40, 87, 0.4);

    .chartBox {
        width: 100%;
        position: relative;

        .chart {
            width: 100%;
            height: 100%;
        }
    }
}
</style>